﻿using AutoMapper;
using BusinessInterface;
using Common;
using Common.Jwt;
using DTOModels.Button;
using DTOModels.Menu;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models.Entity;
using System.Security.Claims;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ApiServer.Controllers.ServiceAPI
{
    /// <summary>
    /// 菜单控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme,Policy ="btnPolicy")]
    public class MenuController : ControllerBase
    {
        private readonly IMenuManagerService _IMenuManagerService;
      
        private readonly IMapper _IMapper;
        private readonly IUserRoleMenuService _IUserRoleMenuService;
     
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMenuManagerService"></param>
        /// <param name="iMapper"></param>
        /// <param name="iUserRoleMenuService"></param>
        public MenuController(IMenuManagerService iMenuManagerService, IMapper iMapper, IUserRoleMenuService iUserRoleMenuService)
        {
            _IMenuManagerService = iMenuManagerService;
            _IMapper = iMapper;
            _IUserRoleMenuService = iUserRoleMenuService;
        }

        /// <summary>
        /// 获取菜单的数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetMenuTreeListAsync()
        {
            //只要能运行到这里，说明权限已经通过了
            //这里能够拿到Userid ,说明token必然已经验证通过了 
            string? strUserId = HttpContext.User?.FindFirst(ClaimTypes.Sid)?.Value;
            if (string.IsNullOrWhiteSpace(strUserId))
            {
                return await Task.FromResult(new JsonResult(new ApiResultData<int>()
                {
                    Message = "没有token权限",
                    Success = false,
                    OValue = 401
                }));
            }

            //根据现有的用户去计算当前用户的菜单的权限
            //穿插点东西----把数据库的结构给大家介绍下
            var menusTreeList = _IMenuManagerService.GetMenusTreeList(Convert.ToInt32(strUserId));
            //ModelDTO
            var result = new JsonResult(new ApiResultData<List<SysRouteTreeDTO>>()
            {
                Data = _IMapper.Map<List<Sys_Menu>, List<SysRouteTreeDTO>>(menusTreeList),
                Success = true,
                Message = "获取菜单列表"
            });
            return await Task.FromResult(result);
        }

        ///// <summary>
        ///// 获取一级菜单
        ///// 默认传递参数为0,无实际业务需求,仅作为路由匹配区别
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[Route("GetCurrentMenuPermission/{menuId:guid}")]
        //public async Task<JsonResult> GetPrimaryMenuListAsync(int id)
        //{
        //    var roleList = _IUserRoleMenuService.Query<Sys_Menu>(c => c.ParentId.Equals(default)).ToList();
        //    var result = new JsonResult(new ApiResultData<List<SysMenuDTO>>()
        //    {
        //        Data = _IMapper.Map<List<Sys_Menu>, List<SysMenuDTO>>(roleList),
        //        Success = true,
        //        Message = "获取一级菜单"
        //    });
        //    return await Task.FromResult(result);
        //}


        /// <summary>
        /// 获取当前的菜单权限
        /// </summary>
        /// <param name="menuManagerService"></param>
        /// <param name="menuId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCurrentMenuPermission/{menuId:guid}")]
        [AllowAnonymous]
        public async Task<JsonResult> GetCurrentMenuPermission(Guid menuId)
        {
            string? strUserId = HttpContext.User?.FindFirst(ClaimTypes.Sid)?.Value;
            if (string.IsNullOrWhiteSpace(strUserId))
            {
                return await Task.FromResult(new JsonResult(new ApiResult()
                {
                    Message = "没有token权限",
                    Success = false
                }));
            }
            ApiResultData<List<SysButtonDTO>> apiResult = await _IMenuManagerService.GetCurrentMenuPermission(Convert.ToInt32(strUserId), menuId);
            JsonResult result = new JsonResult(apiResult);
            return await Task.FromResult(result);
        }



        /// <summary>
        /// 菜单按钮，带层级的树形列表
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet()]
        [Route("{pageindex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageindex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetMenuTreePageAsync(int pageindex, int pageSize, string? searchaString = null)
        {
            PagingData<Sys_Menu> menuspageList = await _IMenuManagerService.GetMenuTreePageAsync(pageindex, pageSize, searchaString);
            PagingData<SysMenuDTO> paging = _IMapper.Map<PagingData<Sys_Menu>, PagingData<SysMenuDTO>>(menuspageList);
            return await Task.FromResult(new JsonResult(new ApiResultData<PagingData<SysMenuDTO>>()
            {
                Data = paging,
                Success = true,
                Message = "菜单树形列表"
            }));
        }

    }
}
